package com.mdd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mdd.common.R;
import com.mdd.pojo.User;
import com.mdd.pojo.vo.SignVo;
import com.mdd.service.UserService;
import com.mdd.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        //验证手机号是否为空
        if (!StringUtils.isNotEmpty(phone)) {
            return R.error("请输入手机号");
        }
        //生成四位验证码
        String sms = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("验证码:" + sms);
        //发送登录验证码信息
        //SMSUtils.sendMessage("瑞吉外卖","SMS_273720420",phone,sms);

        //将生成的验证码放到session中
        //request.getSession().setAttribute(phone, sms);

        //将验证码存放到redis中
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String key = "login:code:"+phone;
        opsForValue.set(key,sms,5, TimeUnit.MINUTES);

        return R.success("验证码发送成功");
    }

    /**
     * 用户手机号登录
     * @param map
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession httpSession) {
        //获取手机号
        String phone = map.get("phone");
        //获取用户输入的验证码
        String code = map.get("code");
//        //获取短信发送的登录验证码
//        String loginCode = (String) httpSession.getAttribute(phone);
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        //从缓存中获取短信验证码
        String key = "login:code:"+phone;
        String loginCode = valueOperations.get(key);
        //验证验证码是否正确，对比成功则可以登录
        if (!code.equals(loginCode) && loginCode != null) return R.error("验证码错误!");
        //验证该手机号是否为新用户，若是新用户则注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setName("user_"+ UUID.randomUUID().toString());
            userService.save(user);
        }
        //将用户信息存到session中
        Long userId = user.getId();
        httpSession.setAttribute("user",userId);
        //用户访问量+1
        HyperLogLogOperations<String, String> logLogOperations = redisTemplate.opsForHyperLogLog();
        logLogOperations.add("UV:",userId.toString());
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 用户签到
     * @return
     */
    @PostMapping("/sign")
    public R<Boolean> userSign(){
       boolean res = userService.userSign();
       return R.success(res);
    }

    @PostMapping("/sign/count")
    public R<SignVo> signCount(){
        return userService.signCount();
    }
}
